document.addEventListener('DOMContentLoaded', function() {
  // DOM元素
  // const baseUrlInput = document.getElementById('baseUrl');
  const startDownloadBtn = document.getElementById('startDownload');
  const fileInput = document.getElementById('fileInput');
  const fileInfo = document.getElementById('file-info');
  const statusDiv = document.getElementById('status');
  const progressContainer = document.querySelector('.progress');
  const progressBar = document.querySelector('.progress-bar');
  
  // 固定下载路径
  const downloadPath = "DownloadedImages";
  
  // 用于存储解析出的图片列表
  let parsedImageList = [];
  // 用于存储下载失败的图片
  let failedDownloads = [];
  
  // 获取默认URL列表
  function getDefaultUrls() {
    const urlElements = document.querySelectorAll('.search-url');
    return Array.from(urlElements).map(el => ({
      url: el.value,
      name: el.dataset.name
    }));
  }
  
  // 处理文件上传
  fileInput.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (!file) {
      fileInfo.textContent = '未选择文件';
      return;
    }
    
    fileInfo.textContent = `已选择文件: ${file.name}`;
    
    // 读取文件内容
    const reader = new FileReader();
    reader.onload = function(e) {
      try {
        // 解析文件内容
        parsedImageList = parseImageListFile(e.target.result);
        fileInfo.textContent = `已解析: ${parsedImageList.length} 个图片项`;
      } catch (error) {
        console.error('解析文件时出错:', error);
        fileInfo.textContent = `解析文件失败: ${error.message}`;
      }
    };
    
    reader.onerror = function() {
      fileInfo.textContent = '读取文件失败';
    };
    
    reader.readAsText(file);
  });
  
  // 解析图片列表文件
  function parseImageListFile(fileContent) {
    const lines = fileContent.split('\n');
    const imageList = [];
    
    // 简单的解析逻辑，假设每行的格式是: 文件名,描述
    for (let line of lines) {
      line = line.trim();
      if (!line || line.startsWith('#')) continue; // 跳过空行和注释行
      
      // 尝试多种分隔符解析
      let parts = [];
      if (line.includes(',')) {
        parts = line.split(',');
      } else if (line.includes('\t')) {
        parts = line.split('\t');
      } else if (line.includes('|')) {
        parts = line.split('|');
      } else {
        // 如果没有明确分隔符，假设第一个空格前是文件名
        const spaceIndex = line.indexOf(' ');
        if (spaceIndex > 0) {
          parts = [line.substring(0, spaceIndex), line.substring(spaceIndex + 1)];
        } else {
          parts = [line, ''];
        }
      }
      
      const filename = parts[0].trim();
      const description = parts.length > 1 ? parts[1].trim() : '';
      
      if (filename) {
        imageList.push({ filename, description });
      }
    }
    
    return imageList;
  }
  
  // 修改保存设置函数，移除baseUrl
  function saveSettings() {
    // 不再需要保存baseUrl
    // chrome.storage.local.set({
    //   baseUrl: baseUrlInput.value
    // });
  }

  // 获取图片文件扩展名
  function getFileExtension(filename) {
    const match = /\.([^.]+)$/.exec(filename);
    return match ? match[1].toLowerCase() : '';
  }

  // 检查URL是否与目标文件扩展名匹配
  function checkUrlExtension(url, targetExt) {
    // 提取URL中的文件扩展名
    const urlExt = getFileExtension(url);
    return urlExt.toLowerCase() === targetExt.toLowerCase();
  }

  // 根据文件扩展名筛选搜索结果
  function filterImageUrlsByExtension(urls, targetExt) {
    // 先尝试精确匹配扩展名
    const exactMatches = urls.filter(url => checkUrlExtension(url, targetExt));
    if (exactMatches.length > 0) {
      return exactMatches[0]; // 返回第一个匹配的URL
    }
    
    // 如果没有精确匹配，直接返回第一个URL
    return urls.length > 0 ? urls[0] : null;
  }

  // 统一处理图片下载
  function downloadImage(item, imageUrl, onComplete) {
    // 获取目标文件扩展名
    const targetExtension = getFileExtension(item.filename);
    
    // 构建保存路径
    let savePath = downloadPath;
    if (savePath && !savePath.endsWith('/')) savePath += '/';
    savePath += item.filename;
    
    // 处理URL以适应目标扩展名
    let processedUrl = imageUrl;
    
    // 检查URL的扩展名与目标扩展名是否匹配
    if (!checkUrlExtension(imageUrl, targetExtension) && targetExtension) {
      console.warn(`警告: 图片URL扩展名与目标扩展名不匹配。URL: ${imageUrl}, 目标: ${targetExtension}`);
      
      // 处理特殊情况，如tukuppt等网站的URL格式问题
      if (imageUrl.includes('tukuppt.com') && imageUrl.includes('!/')) {
        // 移除!/fw/780等后缀参数
        processedUrl = imageUrl.split('!/')[0];
        console.log(`已处理URL: ${processedUrl}`);
      }
      
      // 如果URL中包含查询参数，尝试移除
      if (processedUrl.includes('?')) {
        processedUrl = processedUrl.split('?')[0];
        console.log(`移除查询参数后URL: ${processedUrl}`);
      }
      
      // 为了保持兼容性，我们不修改实际URL的扩展名，
      // 而是根据content-type头来确保浏览器正确处理
    }
    
    // 使用Chrome下载API下载图片
    chrome.downloads.download({
      url: processedUrl,
      filename: savePath,
      saveAs: false,
      conflictAction: 'uniquify'
    }, function(downloadId) {
      if (chrome.runtime.lastError) {
        console.error("下载错误:", chrome.runtime.lastError, processedUrl);
        failedDownloads.push({
          filename: item.filename,
          description: item.description || '',
          reason: chrome.runtime.lastError ? chrome.runtime.lastError.message : '网络错误'
        }); // 添加到失败列表
      }
      
      if (onComplete) onComplete();
    });
  }

  // 从网站搜索图片 - 修改为使用特定的URL
  async function searchImages(siteUrl, keyword, targetExtension) {
    try {
      // 构建搜索URL
      let searchUrl;
      
      if (siteUrl.includes('pixabay.com')) {
        // Pixabay搜索URL
        searchUrl = `${siteUrl}/images/search/${encodeURIComponent(keyword)}/`;
        
        // 如果有目标扩展名，尝试添加到搜索条件中
        if (targetExtension && ['jpg', 'jpeg', 'png', 'gif', 'svg'].includes(targetExtension.toLowerCase())) {
          searchUrl += `?image_type=${targetExtension.toLowerCase()}`;
        }
      } else if (siteUrl.includes('bing.com/images')) {
        // Bing图片搜索URL
        searchUrl = `${siteUrl}${encodeURIComponent(keyword)}`;
      } else {
        // 通用搜索URL
        if (siteUrl.endsWith('/') || siteUrl.endsWith('=')) {
          searchUrl = `${siteUrl}${encodeURIComponent(keyword)}`;
        } else {
          searchUrl = `${siteUrl}/${encodeURIComponent(keyword)}`;
        }
      }
      
      // 发送消息给background.js以获取图片URL
      return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage({
          action: 'searchImages',
          searchUrl: searchUrl,
          targetExtension: targetExtension || '' // 确保始终传递targetExtension参数
        }, response => {
          if (response && response.imageUrls && response.imageUrls.length > 0) {
            resolve(response.imageUrls);
          } else {
            reject(new Error('未找到图片'));
          }
        });
      });
    } catch (error) {
      console.error('搜索图片时出错:', error);
      return [];
    }
  }

  // 使用多个网址尝试搜索图片 - 新增函数
  async function searchImagesWithFallback(keyword, targetExtension) {
    const defaultUrls = getDefaultUrls();
    
    for (const urlData of defaultUrls) {
      try {
        const imageUrls = await searchImages(urlData.url, keyword, targetExtension);
        if (imageUrls && imageUrls.length > 0) {
          // 根据目标扩展名筛选最匹配的URL
          const bestMatch = filterImageUrlsByExtension(imageUrls, targetExtension);
          if (bestMatch) {
            console.log(`在 ${urlData.name} 找到图片: ${keyword}`);
            return bestMatch;
          }
        }
      } catch (error) {
        console.log(`在 ${urlData.name} 搜索失败: ${error.message}`);
        // 继续尝试下一个URL
      }
    }
    
    // 所有URL都尝试失败
    throw new Error(`未在所有网站中找到图片: ${keyword}`);
  }

  // 开始下载图片 - 改为后台处理
  startDownloadBtn.addEventListener('click', function() {
    // 检查文件
    if (parsedImageList.length === 0) {
      statusDiv.textContent = '请先上传并解析图片列表文件';
      return;
    }

    // 发送批量下载任务到后台
    chrome.runtime.sendMessage({
      action: 'startBatchDownload',
      imageList: parsedImageList
    }, response => {
      if (response && response.started) {
        // 显示进度条并初始化
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        statusDiv.textContent = '已开始下载图片，请勿关闭窗口...';
      } else {
        statusDiv.textContent = '启动下载失败: ' + (response && response.error ? response.error : '未知错误');
      }
    });
  });
  
  // 监听后台发来的进度消息
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'batchDownloadProgress') {
      // 确保进度条可见
      progressContainer.style.display = 'block';
      updateProgress(request.current, request.total);
    } else if (request.action === 'batchDownloadComplete') {
      const { success, failed } = request;
      progressBar.style.width = '100%';
      if (failed > 0) {
        statusDiv.textContent = `下载完成！成功 ${success} 张，失败 ${failed} 张，失败列表已自动保存。`;
      } else {
        statusDiv.textContent = `下载任务已全部完成！共 ${success} 张。`;
      }
    }
  });

  // 更新进度条和状态
  function updateProgress(current, total) {
    const progress = Math.round((current / total) * 100);
    progressBar.style.width = progress + '%';
    statusDiv.textContent = `已下载: ${current}/${total} 图片 (${progress}%)`;
  }

  // CSV 字段转义辅助
  function escapeCsvField(val) {
    if (val == null) return '';
    const needQuote = /[",\n]/.test(val);
    let escaped = String(val).replace(/"/g, '""');
    return needQuote ? `"${escaped}"` : escaped;
  }

  // 将下载失败的图片保存为csv文件
  function saveFailedDownloadsToFile() {
    if (failedDownloads.length === 0) return;
    
    // 创建CSV内容 (带BOM)
    let csv = '\uFEFF序号,文件名,描述,原因\n';
    failedDownloads.forEach((item, idx) => {
      const desc = escapeCsvField(item.description || '');
      const reason = escapeCsvField(item.reason || '');
      csv += `${idx + 1},${escapeCsvField(item.filename)},${desc},${reason}\n`;
    });

    const url = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const filename = `未下载成功图片_${timestamp}.csv`;
    
    // 将文件保存到与图片相同的下载目录下
    let savePath = downloadPath;
    if (savePath && !savePath.endsWith('/')) savePath += '/';
    savePath += filename;

    chrome.downloads.download({
      url: url,
      filename: savePath,
      saveAs: false,
      conflictAction: 'uniquify'
    }, () => {
      URL.revokeObjectURL(url);
      statusDiv.textContent += ` 失败列表已保存为 ${savePath}`;
    });
  }
});